package com.xiaowen.controller;

import com.xiaowen.entity.Comment;
import com.xiaowen.service.CommentService;
import com.xiaowen.util.CorrectJsonObject;
import com.xiaowen.util.ErrorJsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by 15c on 2017/11/19.
 */
@Controller
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    CommentService commentService;

    /**
     * 通过travelId查询一条游记的所有评论;可以用于查自己所发全部游记，也可以查询他人
     *
     * @param travelId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listComments", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showListComments(@RequestParam(required = false) Integer travelId) {
        ErrorJsonObject errorJsonObject;
        List<Comment> commentList;
        commentList = commentService.showListComment(travelId);
        if (commentList.isEmpty()) {
            errorJsonObject = new ErrorJsonObject(113, "评价查询失败！");
            return errorJsonObject.toJSONString();
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("评价查询成功！");
        correctJsonObject.setData(commentList);
        return correctJsonObject.toString();
    }

    /**
     * 用于发表评论(必须给与游记Id与评价用户Id，不然查询时结果为空值)
     *
     * @param comment 评论对象
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String createNewComments(@RequestBody(required = false) Comment comment) {
        ErrorJsonObject errorJsonObject;
        //评论内容不能让为空，并且确保游记Id与评价用户Id不为空；前端进行判断
        int i = commentService.addComments(comment);
        if (1 != i) {
            errorJsonObject = new ErrorJsonObject(114, "评价发表失败！");
            return errorJsonObject.toJSONString();
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("评价发表成功！");
        correctJsonObject.setData(0);
        return correctJsonObject.toString();
    }

    /**
     * 用于删除评论(必须给userId)
     * @param userCommentId 创建这条评价的用户Id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteComments(@RequestParam(required = false) Integer userCommentId) {
        ErrorJsonObject errorJsonObject;
        //确保游记Id与评价用户Id不为空进行判断是否有删除权利；前端进行判断
        int i =commentService.deleteComments(userCommentId);
        if (1 != i) {
            errorJsonObject = new ErrorJsonObject(115, "评价删除失败！");
            return errorJsonObject.toJSONString();
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("评价删除成功！");
        correctJsonObject.setData(0);
        return correctJsonObject.toString();
    }
}
